<?php
namespace app\api\controller;

use app\common\controller\ApiController;
use think\App;
use think\facade\Db;
use app\api\model\Token;

class Shop extends ApiController
{
    protected $noNeedLogin = [
        "user_register",
        "user_login"
    ];
    protected $mustLogin = [];
    protected $counter = 0;

    use \app\admin\traits\Curd;
    public function __construct(App $app)
    {
        parent::__construct($app);
    }
    //询问问题添加记录
    public function test(){
        $param = $this->request->param();
        if (empty($param['content'])) {
            $this->error('未找到指定参数');
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api.openai-hk.com/v1/chat/completions');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 忽略SSL证书验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 忽略SSL证书CN域验证
        $headers = array();
        $headers[] = 'Content-Type: application/json';
        $headers[] = 'Authorization: Bearer hk-ckl9mn1000033029c474eec3d51cee10dccfdc74828fb067';
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $data = array(
            'max_tokens' => 1200,
            'model' => 'gpt-3.5-turbo',//gpt-3.5-turbo  gpt-4-0613
            'temperature' => 0.8,
            'top_p' => 1,
            'presence_penalty' => 1,
            'messages' => array(
                array(
                    'role' => 'system',
                    'content' => 'You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible.'
                ),
                array(
                    'role' => 'user',
                    'content' => $param['content']//你是chatGPT多少
                )
            )
        );
        $data_string = json_encode($data);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }
        curl_close($ch);
        $result = json_decode($result);
        if(!empty($result->error)){
            $this->error($result->error->message);
        }

 
        //加入记录表
        if(empty($param['ask_id'])){
            //新增新的问题
            $data_add = [
                "uid"=>$this->uid,
                "problem"=>$param["content"],
                "answer"=>$result->choices[0]->message->content
            ];
            Db::name("asking_questions")->insert($data_add);
            $insertId = Db::name('asking_questions')->getLastInsID();
            $result->ask_id = $insertId;
        }else{
            //原问题下新增新的问题
            $data_jiuadd = [
                "ask_id"=>$param["ask_id"],
                "problem"=>$param["content"],
                "answer"=>$result->choices[0]->message->content
            ];
            Db::name("asking_questions_detail")->insert($data_jiuadd);
            $result->ask_id = 0;
        }
        $list = [];
        $list["value"] = $result->choices[0]->message;
        $list["ask_id"] = $result->ask_id;
        $this->success("获取成功",$list);
     }
 

     //问题列表
     public function personal_problem_list(){
        $param = $this->request->param();
        $where = [];
        if(!empty($param['problem']) && isset($param['problem']))
        {
            $where[] = [
                ['problem', 'like', '%'.$param['problem'].'%']
            ];
        }
        $list = Db::name("asking_questions")->where($where)->where("uid",$this->uid)->select();
        $this->success("获取成功",$list);
     }

     //问题列表详情
     public function personal_problem_detail(){
        $param = $this->request->param();
        if (empty($param['ask_id'])) {
            $this->error('参数不能为空');
        }
        $newlist = Db::name("asking_questions")->where("id",$param['ask_id'])->find();
        $asking_questions_detail = Db::name("asking_questions_detail")->where("ask_id",$param['ask_id'])->select();
        $asking_questions_detail = $asking_questions_detail->toArray();
        array_unshift($asking_questions_detail, $newlist);
        $this->success("获取成功",$asking_questions_detail);
     }
     

     //修改标题名称
     public function edit_title(){
        $param = $this->request->param();
        if (empty($param['content'])) {
            $this->error('标题不能为空');
        }
        if (empty($param['id'])) {
            $this->error('未找到指定参数');
        }
        Db::name("asking_questions")->where("id",$param["id"])->update(["problem"=>$param["content"]]);
        $this->success("操作成功");
     }

     //删除标题
     public function del_title(){
        $param = $this->request->param();
        if (empty($param['ask_id'])) {
            $this->error('参数不能为空');
        }
        Db::name("asking_questions")->where("id",$param['ask_id'])->delete();
        Db::name("asking_questions_detail")->where("ask_id",$param['ask_id'])->delete();
        $this->success("操作成功");
     }

    /**
     * @NodeAnotation(title="批量删除")
     */
    public function batch_delete()
    {
        $param = $this->request->param();
        if (empty($param['ask_id'])) {
            $this->error('参数不能为空');
        }
        $row = Db::name("asking_questions")->whereIn('id', $param['ask_id'])->select();
        if(empty($row)){
            $this->error('数据不存在');
        }
        try {
            foreach($param['ask_id'] as $k=>$v){
                Db::name("asking_questions")->where("id",$v['ask_id'])->delete();
                Db::name("asking_questions_detail")->where("ask_id",$v['ask_id'])->delete();
            }
            $save = true;
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }


    //用户登录
    public function user_login()
    {
        $param = $this->request->param();
        if (empty($param['username'])) {
            $this->error("登陆失败,账号不能为空");
        }
        if (empty($param['password'])) {
            $this->error("登陆失败,密码不能为空");
        }

        $flag = Db::name("user_manag_account")->where("username",$param["username"])->find();
        if(empty($flag)){
            $this->error("登陆失败,账户不存在");
        }
        if($flag["status"] == 1){
            $this->error("登陆失败,账户已锁定");
        }
        if($flag["password"] != md5($param["password"])){
            $this->error("登陆失败,密码错误");
        }
        $token = Auth::makeToken();
        $userToken = new Token();
        $userToken->setToken($token, $flag["id"], $this->method);
        $this->success('登录成功', ['token' => $token, 'method' => $this->method, 'uid' => $flag["id"], 'user_info' => $flag]);
    }


    //用户注册
    public function user_register()
    {
          $param = $this->request->param();
          if (empty($param['username'])) {
              $this->error("注册失败,账号不能为空");
          }
          if (empty($param['password'])) {
              $this->error("注册失败,密码不能为空");
          }
          if (empty($param['new_password'])) {
            $this->error("注册失败,确认密码不能为空");
          }

          if($param['password'] != $param['new_password']){
            $this->error("注册失败,两次密码不一致");
          }
  
        $flag = Db::name("user_manag_account")->where("username",$param["username"])->find();
        if(!empty($flag)){
            $this->error("注册失败,账户已存在");
        }
        $info = [
            "username"=>$param["username"],
            "password"=>md5($param["password"]),
            "create_time"=>time()
        ];

        Db::name("user_manag_account")->insert($info);
        $userId = Db::name("user_manag_account")->getLastInsID();
        $info = $info;
        $token = Auth::makeToken();
        $userToken = new Token();
        $userToken->setToken($token, $userId, $this->method);
        $user_info = ['username' => $param["username"], "uid"=>$userId];
        $this->success('注册成功', ['token' => $token, 'method' => $this->method, 'user_info' => $user_info]);
    }



     
     

   
     

    
 
   
}
